import type {AxiosInstance, AxiosRequestConfig, AxiosResponse} from 'axios'
import axios from 'axios'
import {ElMessage} from 'element-plus'
import {getToken, removeToken} from './auth'
import router from '@/router'
import type {ApiResponse} from '@/types/common'

// 创建axios实例
const service: AxiosInstance = axios.create({
  baseURL: '/api', // 通过vite代理到后端
  timeout: 15000, // 请求超时时间
  headers: {
    'Content-Type': 'application/json;charset=UTF-8'
  }
})

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    // 添加token到请求头
    const token = getToken()
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    console.error('请求错误:', error)
    return Promise.reject(error)
  }
)

// 统一响应处理函数
const handleResponse = <T>(response: AxiosResponse<ApiResponse<T>>): T => {
  const { data } = response
  
  // 如果是文件下载等特殊响应，直接返回
  if (response.config.responseType === 'blob') {
    return response as any
  }
  
  // 检查响应格式
  if (!data || typeof data !== 'object') {
    ElMessage.error('响应格式错误')
    throw new Error('响应格式错误')
  }
  
  // 成功响应处理
  if (data.code === 200 && data.success) {
    return data.data
  }
  
  // 业务错误处理
  const errorMessage = data.message || '请求失败'
  ElMessage.error(errorMessage)
  throw new Error(errorMessage)
}

// 响应拦截器
service.interceptors.response.use(
  (response: AxiosResponse<ApiResponse>) => {
    return handleResponse(response)
  },
  (error) => {
    console.error('响应错误:', error)
    
    let message = '网络错误，请稍后重试'
    
    if (error.response) {
      const { status, data } = error.response
      
      switch (status) {
        case 401:
          message = '登录已过期，请重新登录'
          // 清除token并跳转到登录页
          removeToken()
          router.push('/login')
          break
        case 403:
          message = '没有权限访问该资源'
          break
        case 404:
          message = '请求的资源不存在'
          break
        case 500:
          message = '服务器内部错误'
          break
        default:
          message = data?.message || `请求失败 (${status})`
      }
    } else if (error.code === 'ECONNABORTED') {
      message = '请求超时，请稍后重试'
    } else if (error.message === 'Network Error') {
      message = '网络连接失败，请检查网络设置'
    }
    
    ElMessage.error(message)
    return Promise.reject(error)
  }
)

// 封装请求方法
export const request = {
  get<T = any>(url: string, config?: AxiosRequestConfig): Promise<T> {
    return service.get(url, config)
  },
  
  post<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> {
    return service.post(url, data, config)
  },
  
  put<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> {
    return service.put(url, data, config)
  },
  
  delete<T = any>(url: string, config?: AxiosRequestConfig): Promise<T> {
    return service.delete(url, config)
  },
  
  patch<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> {
    return service.patch(url, data, config)
  }
}

export default service